<template>
    <el-dialog :title="title" :visible.sync="visible" :width="width" :close-on-click-modal="closeOnClickModal" append-to-body :show-close="showClose">
        <el-upload ref="upload" :limit="1" :action="action" :data="actionParam" :multiple="false" :show-file-list="showFileList" :auto-upload="autoUpload" accept=".xlsx,.xls"
            :headers="headers" :on-success="uploadSuccess" :before-upload="uploadBefore" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" v-if="showDownTemplate" @click="downloadTemplate">下载模板</el-link>
                <br>
                <slot></slot>
            </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" v-if="showSubmitButton" @click="submit">确 定</el-button>
            <el-button @click="visible = false">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
/**
 * 自定义事件列表
 * emits:['import-success']
 *      import-success : 导入成功之后执行的事件
 * 
 * slot
 *      支持自定义插槽内容
 * 
 * 
 * 
 */
import { getToken } from "@/utils/auth";
import store from '@/store'

export default {
    name: 'ImportExcel',
    props: {
        title: {//弹框标题
            type: String,
            default: "导入数据"
        },
        width: {//弹框宽度
            type: String,
            default: "400px"
        },
        showClose: {//是否显示右上角关闭按钮
            type: Boolean,
            default: false
        },
        closeOnClickModal: {//点击四周是否关闭
            type: Boolean,
            default: false
        },
        autoUpload: {//是否在选取文件后立即进行上传 [true|false]
            type: Boolean,
            default: true
        },
        data: {//导入接口的参数
            type: Object,
            default: () => { }
        },
    },
    data() {
        return {
            action: '',//上传的地址
            visible: false,//是否显示
            headers: {
                Authorization: "Bearer " + getToken()
            },
            showDownTemplate: true,//是否显示 模板下载 按钮。  true:显示(必须配置模板的下载地址)  false:不显示
            downTemplateUrl: undefined,//模板下载 地址
            downTemplateMethod: 'get',//模板下载 方式 [get|post]
            downTemplateParam: {},//模板下载 参数
        }
    },
    computed: {
        showFileList: function () {
            return !this.autoUpload;
        },
        showSubmitButton: function () {
            return !this.autoUpload;
        },
        actionParam: function () {
            let p = {};
            if(this.data){
                let dp = this.data;
                Object.keys(dp).forEach(k => { if (dp[k]) p[k] = dp[k] });
            }
            return p;
        },
    },
    created: function () {
    },
    methods: {
        submit() {
            this.$refs.upload.submit();
        },
        uploadBefore(file) {//上传之前的处理
            if (this.showDownTemplate && !this.downTemplateUrl) {
                this.$modal.msgError("未设置模板下载地址。。。");
                this.$refs.upload.clearFiles();
                return false;
            }
            this.$modal.loading("数据正在导入中，请稍候...");
        },
        uploadSuccess(response, file, fileList) {//上传成功
            if (response.code === 200) {
                this.visible = false;
            }
            if (response.code === 500) {
                this.$modal.msgError(response.msg);
            }
            if (response.code === 401) {
                this.$modal.msgError(response.msg);
                store.dispatch('LogOut').then(() => {
                    location.href = location.href;
                })
            }
            this.$refs.upload.clearFiles();
            this.$modal.closeLoading();
            if ('import-success' in this.$listeners) {
                this.$emit('import-success');
            }
        },
        uploadError(err, file, fileList) {//上传失败
            this.$refs.upload.clearFiles();
            this.$modal.closeLoading();
            this.$modal.msgError("导入失败，请重试");
        },
        downloadTemplate() {//下载模板
            let config = {
                url: this.downTemplateUrl,
                method: this.downTemplateMethod,
                data: this.downTemplateParam,
            }
            let url = this.downTemplateUrl;
            if (url) {
                let fileName = null;
                if (url.lastIndexOf("/") > -1) {
                    fileName = url.slice(url.lastIndexOf("/") + 1);
                    if (fileName.lastIndexOf(".") > -1) {
                        config.fileName = fileName;
                    }
                }
            }

            this.$download.downloadFile(config);
        },
    }
}
</script>